#require 'digest/sha1'

class AdminUser < ActiveRecord::Base
  validates_presence_of :user_name
  validates_uniqueness_of :user_name
  
  #attr_accessible :user_name
  
  class << self
  
    def authenticate(user_name, password)
      user = find_by_user_name(user_name)
      if user and user.crypted_password != encrypted_password(password, user.salt)
        user = nil
      end
      user
    end
    
  end
  
  def to_s
    user_name
  end
  
  def password
    @password
  end
  
  def password=(pwd)
    @password = pwd
    create_new_salt
    self.crypted_password = self.class.encrypted_password(self.password, self.salt)
  end
  
  def del
    update_attributes!(:status => -1)
  end
  
  private
  
    def self.encrypted_password(pwd, salt)
      Digest::SHA1.hexdigest("#{pwd}lwk-kqy-lz#{salt}")
    end

    def create_new_salt
      self.salt = Digest::SHA1.hexdigest(Time.now.to_s + rand.to_s)
    end
    
#    #TODO delete admin has bug if not comment this
#    def validate
#      errors.add_to_base('密码不能为空!') if self.password.blank?
#    end
end
